package tests;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class HtmlRaportOutput {

	private List<TestResult> testResults = new LinkedList<TestResult>();

	public void GetTestResult(TestResult testResult) {

		testResults.add(testResult);

	}

	private void PrintTestResults(PrintStream ps) {
		ps.println("<table class=\"sofT\" cellspacing=\"0\">"
				+ "<tr><td colspan=\"10\" class=\"helpHed\">"
				+ "Test results for: " + (new Date()) + "</td></tr>");
		ps.println("<tr><td class=\"helpHed\">Test name</td>"
				+ "<td class=\"helpHed\">Term Number</td>"
				+ "<td class=\"helpHed\">Value</td>"
				+ "<td class=\"helpHed\">Proved Value</td>"
				+ "<td class=\"helpHed\">Time Used [msec]</td>"
				+ "<td class=\"helpHed\">Memory Used [B]</td>"
				+ "<td class=\"helpHed\">Graph Size</td>"
				+ "<td class=\"helpHed\">Graph Avg. Depth</td>"
				+ "<td class=\"helpHed\">Graph Max. Depth</td></tr>");

		int testCounter = 0;
		String prevTestName = "";

		Iterator<TestResult> iter = testResults.iterator();
		while (iter.hasNext()) {
			TestResult tr = iter.next();

			if (tr instanceof SensibleTestResult) {
				SensibleTestResult str = (SensibleTestResult) tr;

				if (str.name.equals(prevTestName))
					++testCounter;
				else
					testCounter = 0;

				ps.println("<tr><td >" + str.name + "</td><td >" + testCounter
						+ "</td><td "
						+ (str.value == str.provedValue ? "" : "class=\"sup\"")
						+ ">" + (str.value ? "coherent" : "incoherent")
						+ "</td><td "
						+ (str.value == str.provedValue ? "" : "class=\"sup\"")
						+ ">" + (str.provedValue ? "coherent" : "incoherent")
						+ "</td><td >" + str.timeUsed + "</td><td >"
						+ str.memoryUsed + "</td><td >" + str.graphSize
						+ "</td><td >" + (int) str.graphAvgDepth + "</td><td >"
						+ str.graphMaxDepth + "</td></tr>");

				prevTestName = str.name;
			} else {

				if (tr.name.equals(prevTestName))
					++testCounter;
				else
					testCounter = 0;

				ps
						.println("<tr><td >"
								+ tr.name
								+ "</td><td >"
								+ testCounter
								+ "</td><td colspan=7 class=\"sup\"> TIMEOUT </td></tr>");

				prevTestName = tr.name;

			}

		}

		ps.println("</table>");
	}

	public void OutputHtmlRaport(String proverType, PrintStream ps) throws IOException {

		FileReader htmlTemplateFile = new FileReader(
				"tests/raport_templates/html.template");

		BufferedReader htmlTemplateBR = new BufferedReader(htmlTemplateFile);

		String s = "";
		while (true) {
			s = htmlTemplateBR.readLine();
			if (s == null)
				break;
			else if (s.equals("<< DATA >>"))
				PrintTestResults(ps);
			else if (s.equals("<< PROVER >>")) 
				ps.println(proverType);
			else
				ps.println(s);
		}

	}
}
